<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 运费设置
 */
namespace app\bestbao\controller\admin;
use app\bestbao\model\BestbaoConfig;
use app\common\controller\Admin;
use think\facade\Request;

class Cost extends Admin{

    public function initialize() {
        parent::initialize();
        $this->assign('pathMaps',[['name'=>'费用设置','url'=>url("bestbao/admin.cost/index")]]);
    }


    /**
     * 应用列表
     */
    public function index(){
        $view['lists'] = BestbaoConfig::MiniappLists();
        return view()->assign($view);
    }

    /**
     *  应用配置
     * @return void
     */
    public function config(){
        if(request()->isAjax()){
            $miniapp_id = Request::param('miniapp_id/d');
            if(!isset($miniapp_id)){
                $this->error('应用未找到');
            }
            $data = [
                'type'              => input('post.type/d'),
                'price'             => input('post.price/s'),
                'member_miniapp_id' => $miniapp_id,
            ];
            $validate = $this->validate($data,'cost.save');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            if($data['type'] == 0 && empty($data['price'])){
                return json(['code'=>0,'msg'=> '价格必须填写']);
            }
            $result = BestbaoConfig::where(['member_miniapp_id' => $miniapp_id])->find();
            if($result){
                $result->type              = $data['type'];
                $result->price             = $data['price'];
                $result->member_miniapp_id = $miniapp_id;
                $result->save();
            }else{
                $data['create_time'] = time();
                $result = BestbaoConfig::create($data);
            }
            if($result){
                return json(['code'=>200,'url' => url('admin.cost/index'),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            $miniapp_id = (int)Request::param('miniapp_id');
            $view['info']  = BestbaoConfig::where(['member_miniapp_id' => $miniapp_id])->find();
            $view['miniapp_id']  = $miniapp_id;
            return view()->assign($view);
        }
    }
}